/**
 * Created by tdzl2003 on 10/15/16.
 */

import {
  Modifier,
  EditorState,
} from 'draft-js';
import {Map} from 'immutable';

import styles from './RichEdit.less';

export function getBlockStyle(block) {
  const data = block.getData();
  switch (data && data.get('align')) {
    case 'left':
      return styles.alignLeft;
    case 'center':
      return styles.alignCenter;
    case 'right':
      return styles.alignRight;
    default:
      return null;
  }
}

export function setAlign(editorState, align) {
  const currentContent = editorState.getCurrentContent();
  const selection = editorState.getSelection();
  return EditorState.push(editorState, setContentAlign(currentContent, selection, align), 'change-block-data');
}

export function setContentAlign(currentContent, selection, align) {
  const newContent = Modifier.mergeBlockData(currentContent, selection, Map({
    align: align,
  }));
  return newContent;
}

export function getAlign(editorState) {
  const currentContent = editorState.getCurrentContent();
  const selection = editorState.getSelection();
  const focusKey = selection.getFocusKey();
  const focusBlock = currentContent.getBlockForKey(focusKey);
  const blockData = focusBlock.getData();
  return blockData && blockData.get('align');
}
